"""
Case Type   : 工具方法
Case Name   : 流控参数验证
Create At   : 2025/03/25
Owner       : @chen
Description :
Expect      :
History     :
"""

import unittest

from yat.test import macro

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger
from yat.test import Node

class rbcu(unittest.TestCase):
    def __init__(self, node_name='dbuser'):
        # root用户还是数据库安装的用户执行脚本。数据库用户默认dbuser（见conf/nodes.yml）
        self.logger = Logger()
        self.com = Common()
        self.constant = Constant()
        self.sh_primy = CommonSH(node_name)

    def set_rto(self, display=False):
        dic = {}
        if display:
            recovery_parse_workers = self.com.show_param('recovery_parse_workers')
            recovery_redo_workers = self.com.show_param('recovery_redo_workers')
            hot_standby = self.com.show_param('hot_standby')
            dic['recovery_parse_workers'] = recovery_parse_workers
            dic['recovery_redo_workers'] = recovery_redo_workers
            dic['hot_standby'] = hot_standby
        set_param = self.sh_primy.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f"recovery_parse_workers = 4")
        self.logger.info(set_param)
        self.assertTrue(set_param, '参数修改异常')
        set_param = self.sh_primy.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f"recovery_redo_workers = 4")
        self.logger.info(set_param)
        self.assertTrue(set_param, '参数修改异常')
        set_param = self.sh_primy.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f"hot_standby = off")
        self.logger.info(set_param)
        self.assertTrue(set_param, '参数修改异常')
        return dic

    def set_real_time(self, node_name, display=False):
        dic = self.set_rto(display)
        if display:
            ss_enable_ondemand_recovery = self.com.show_param('ss_enable_ondemand_recovery')
            ss_enable_ondemand_realtime_build = self.com.show_param('ss_enable_ondemand_realtime_build')
            dic['ss_enable_ondemand_recovery'] = ss_enable_ondemand_recovery
            dic['ss_enable_ondemand_realtime_build'] = ss_enable_ondemand_realtime_build
        set_param = self.sh_primy.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f"ss_enable_ondemand_recovery = on", 
                                             node_name)
        self.logger.info(set_param)
        self.assertTrue(set_param, '参数修改异常')
        set_param = self.sh_primy.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f"ss_enable_ondemand_realtime_build = on", 
                                             node_name)
        self.logger.info(set_param)
        self.assertTrue(set_param, '参数修改异常')
        return dic

    def restore_guc_param(self, node_name, dic):
        guc_list = ['recovery_redo_workers', 'recovery_parse_workers', 
            'hot_standby', 'recovery_time_target']
        for key in dic.keys():
            hostname = node_name
            if key in guc_list:
                hostname = 'all'
            set_param = self.sh_primy.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f"{key} = {dic[key]}", 
                                             hostname)
            self.logger.info(set_param)
            self.assertTrue(set_param, '参数修改异常')

    def set_control(self, node_name, target, display=False):
        dic = {}
        if display:
            recovery_time_target = self.com.show_param('recovery_time_target')
            dic['recovery_time_target'] = recovery_time_target
        set_param = self.sh_primy.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f"recovery_time_target = {target}", 
                                             node_name)
        self.logger.info(set_param)
        self.assertTrue(set_param, '参数修改异常')
        return dic

    def control_check(self, node, inst_name, log_path=macro.PG_LOG_PATH):
        inst_name = f'dn_{inst_name}'
        cmd = f"cd {log_path}/{inst_name} && ls -lt | grep -v total | head -n 1 | awk " \
            f"'{{{{print $9}}}}'"
        self.logger.info(cmd)
        result = node.sh(cmd).result().strip()
        self.logger.info(result)
        cmd = f"cd {log_path}/{inst_name} && grep 'Get realtime-build' {result}"
        self.logger.info(cmd)
        result = node.sh(cmd).result().strip()
        self.logger.info(result)
        return result

    def send_control_check(self, node, inst_name, log_path=macro.PG_LOG_PATH):
        inst_name = f'dn_{inst_name}'
        cmd = f"cd {log_path}/{inst_name} && ls -lt | grep -v total | head -n 1 | awk " \
            f"'{{{{print $9}}}}'"
        self.logger.info(cmd)
        result = node.sh(cmd).result().strip()
        self.logger.info(result)
        cmd = f"cd {log_path}/{inst_name} && grep 'realtime-build ptr start' {result}"
        self.logger.info(cmd)
        result = node.sh(cmd).result().strip()
        self.logger.info(result)
        return result
    
    def query_view(self, node_sh):
        sql = 'select * from realtime_build_log_ctrl_status()'
        ret = node_sh.execut_db_sql(sql)
        self.logger.info(ret)
        return ret
